package com.kun.controller.admin;


import com.kun.entity.Blogger;
import com.kun.result.Result;
import com.kun.service.impl.BloggerServiceImpl;
import com.kun.util.SysConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SunKun
 * @since 2021-06-14
 */
@RestController
@CrossOrigin(origins = "http://localhost:8006",allowCredentials = "true")  //允许跨域
@ResponseBody
@RequestMapping("/kun/admin/blogger")
public class BloggerController {
    @Autowired
    BloggerServiceImpl bloggerService;

    /**
     * 博主登录
     * @param blogger
     * @return
     */
    @PostMapping("/signIn")
    public Result signIn(@RequestBody Blogger blogger,
                         HttpServletResponse response){
        try {
            Blogger queryBlogger = bloggerService.queryBlogger(blogger);
            Cookie cookie = new Cookie("blogger",SysConstant.BLOGGER_COOKIE);
            cookie.setPath("/");
            cookie.setMaxAge(6060);
            response.addCookie(cookie);
            return Result.ok().data("blogger",queryBlogger);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error().message(e.getMessage());
        }
    }

    /**
     * 注销登录
     * @param
     * @return
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request,
                         HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        System.out.println("cookie的长度 " + cookies.length);
        for (Cookie cookie : cookies) {//遍历所有Cookie
            System.out.println("cookie : "+cookie.getName() + " : " + cookie.getValue());
            if (cookie.getName().equals("blogger")) {//找到对应的cookie
                cookie.setMaxAge(0);//Cookie并不能根本意义上删除，只需要这样设置为0即可
                cookie.setPath("/");//很关键，设置成跟写入cookies一样的，全路径共享Cookie
                response.addCookie(cookie);//重新响应
            }
        }
        return Result.ok();
    }

    @RequestMapping("/test")
    public void test() {
//        Cookie cookie = new Cookie("user","user");
//        cookie.setPath("/");
//        cookie.setMaxAge(6060);
//        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8006");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.addCookie(cookie);
    }
}

